<template>
  <div class="operation-menu-wrapper" :class="'file-type-' + fileType().current()">
    <el-button-group class="operate-group">
      <el-button size="mini" type="primary" icon="el-icon-upload2" id="uploadFileId" @click="upload()"
                 >上传
      </el-button>
      <el-button size="mini" type="primary" icon="el-icon-plus" @click="addFolder()">新建文件夹
      </el-button>
      <el-button size="mini" type="primary" :disabled="!selectionFile.length" icon="el-icon-delete"
                 @click="deleteSelectedFile()">批量删除
      </el-button>
      <el-button size="mini" type="primary" :disabled="!selectionFile.length" icon="el-icon-download"
                 @click="recoverSelectedFile()" v-if="fileType().isRecycle()">批量恢复
      </el-button>
      <el-button size="mini" type="primary" :disabled="!selectionFile.length" icon="el-icon-rank"
                 @click="moveSelectedFile()">批量移动
      </el-button>
      <!--            <el-button size="mini" icon="el-icon-document-copy">拷贝</el-button>-->
      <el-button size="mini" type="primary" :disabled="!selectionFile.length" icon="el-icon-download"
                 @click="downloadSelectedFile()" v-if="fileType().isNotRecycle()">批量下载
      </el-button>
    </el-button-group>

    <!-- 全局搜素文件 -->
    <el-input
        class="select-file-input"
        v-model="searchFile.filename"
        placeholder="搜索您的文件"
        size="mini"
        maxlength="255"
        :clearable="true"
        @change="handleSearchInputChange"
        @clear="emit('getTableDataByType')"
        @keyup.enter.native="handleSearchInputChange(searchFile.filename)"
    >
      <i slot="prefix" class="el-input__icon el-icon-search" title="点击搜索" @click="handleSearchClick"></i>
    </el-input>


    <!-- 批量操作 -->
    <el-button
        class="batch-opera-btn"
        :type="batchOperate ? 'primary' : ''"
        icon="el-icon-finished"
        size="mini"
        v-if="fileModel().isGrid()"
        @click="changeBatchOperate()"
    >
      {{ batchOperate ? '取消批量操作' : '批量操作' }}
    </el-button>


    <!-- 文件展示模式 -->
    <div class="change-file-model">
      <el-radio-group v-model="fileGroupLable" size="mini" @change="changeFileDisplayModel">
        <el-radio-button :label="0"><i class="el-icon-tickets"></i> 列表</el-radio-button>
        <el-radio-button :label="1"><i class="el-icon-s-grid"></i> 网格</el-radio-button>
        <el-radio-button :label="2" v-if="fileType().isImage()"><i class="el-icon-date"></i> 时间线</el-radio-button>
      </el-radio-group>
    </div>

    <!-- 选择表格列 -->
    <SelectColumn class="select-column"></SelectColumn>

    <!-- 多选文件下载，页面隐藏 -->
    <a
        target="_blank"
        v-for="(item, index) in selectionFile"
        :key="index"
        :href="getDownloadPath(item.id)"
        :download="item.filename + '.' + item.extension"
        :title="'downloadLink' + index"
        :ref="'downloadLink' + index"
    ></a>
  </div>
</template>

<script>

import {
  batchDeleteFile, batchRecoverRecycle, batchDeleteRecoveryFile, makeDir
} from '/@/request/file.js'
import SelectColumn from './SelectColumn.vue'

import { wangpanGlobal }  from '/@/utils/wangpanGlobalConst';
import {filePath,fileModel,fileType, getDownloadPath} from '/@/utils/wangpanGlobalFunction';
import { computed, getCurrentInstance, onMounted, reactive, toRefs } from 'vue';
import { useStore } from '/@/store/index';
import { ElMessage, ElMessageBox } from 'element-plus';

export default {
  name: 'OperationMenu',
  emits:['getTableDataByType','setMoveFileDialogData','getSearchFileList','update:batchOperate'],
  props: {
    selectionFile: Array,
    operationFile: Object,
    batchOperate: Boolean //  批量操作模式
  },
  components: {
    SelectColumn
  },
  setup(props,{ emit }){
  
  	const store=useStore();	
	const { proxy } = getCurrentInstance();
	
  	const state = reactive({
      // 文件搜索数据
      searchFile: {
        filename: ''
      },
      fileTree: [],
      batchDeleteFileDialog: false,
      fileGroupLable: wangpanGlobal.gFILE_MODEL.TABLE, //  文件展示模式
    });

	const uploadFileData = computed(()=>{		
        let data = {
          folderId: filePath().current(),
          isDir: false
        }
        if (!data.folderId) {
          delete data.folderId
        }
        return data;
    });
    
    const upload=()=> {
      // 打开文件选择框
      proxy.mittBus.emit('openUploader', uploadFileData.value)
    };
    //  新建文件夹按钮：打开模态框
     
    const addFolder=()=> {
      ElMessageBox.prompt('请输入文件夹名称', '创建文件夹', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern:/^[^\/:*?"<>|]+/,
        inputErrorMessage: '错误的命名',
      }).then(({value}) => {
      	ElMessage({
          type: 'info',
          message: '正在建立'
        })
        createFolder(value)
      }).catch(() => {
        ElMessage({
          type: 'info',
          message: '取消输入'
        })
      })
    };
    
    //  新建文件夹模态框-确定按钮
    const createFolder=(filename)=> {
      console.log(filename)
      let data = {
        name: filename,
      }
      console.log('path:'+filePath().current())
      if (filePath().current()) {
        data.pid = filePath().current()
      }
      console.log(data)
      makeDir(data).then(() => {
        ElMessage.success('添加成功')
        console.log('添加成功')
        emit('getTableDataByType')
      }).catch(err => {
      ElMessage.warning('创建目录错误')
      });
    };
	
    //  批量操作-删除按钮
    const deleteSelectedFile=()=> {
      let data = {
        userFileIds: props.selectionFile.flatMap(row => row.id)
      }
      let deleteApi;
      if (fileType().isNotRecycle()){
        deleteApi = batchDeleteFile
      }else{
        deleteApi = batchDeleteRecoveryFile
      }
      //  批量删除接口
      deleteApi(data).then(() => {
        ElMessage({
          message: "文件删除成功",
          type: 'success'
        })
        emit('getTableDataByType')
        store.dispatch('wangpanSideMenu/showStorage')
      }).catch(err => {
        console.error(err)
        ElMessage.error("系统忙，删除失败")
      })
    };
    
    const recoverSelectedFile=()=>{
      let data = {
        userFileIds: props.selectionFile.flatMap(row => row.id)
      }
      //  批量恢复接口
      batchRecoverRecycle(data).then(() => {
        ElMessage({
          message: "删除文件已恢复",
          type: 'success'
        })
        emit('getTableDataByType')
        store.dispatch('wangpanSideMenu/showStorage')
      }).catch(err => {
        console.error(err)
        ElMessage.error("系统忙，恢复失败")
      })
    };
    
    //  批量操作-移动按钮
    const moveSelectedFile=()=> {
      emit('setMoveFileDialogData', true, true)
    };
    //  批量操作：下载按钮
    const downloadSelectedFile=()=> {
      for (let i = 0; i < props.selectionFile.length; i++) {
        let name = 'downloadLink' + i
        proxy.$refs[name].click()
      }
    };
    const handleSearchInputChange=(value)=> {
      if (value === '') {
        emit('getTableDataByType')
      } else {
        emit('getSearchFileList', value)
      }
    };
    // 图片网格模式下 - 批量操作切换
    const changeBatchOperate=()=> {
      emit('update:batchOperate', !props.batchOperate)
    };
    // 切换文件查看模式
    const changeFileDisplayModel = (label)=> {
      store.commit('wangpanFileList/changeFileModel', label)
    };
    const handleSearchClick=()=> {
      emit('getSearchFileList', state.searchFile.filename)
    };

    onMounted(async ()=>{
	    state.fileGroupLable = fileModel().current();
	    proxy.mittBus.on('refreshList', () => {
	      emit('getTableDataByType')
	    });
	    proxy.mittBus.on('refreshStorage', () => {
	      store.dispatch('wangpanSideMenu/showStorage')
	    });
    });

    return{
    	changeFileDisplayModel,
    	upload,
    	addFolder,
    	deleteSelectedFile,
    	recoverSelectedFile,
    	moveSelectedFile,
    	downloadSelectedFile,
		handleSearchInputChange,
    	changeBatchOperate,
    	handleSearchClick,
    	getDownloadPath,
    	...toRefs(state),
    	fileType,
    	fileModel,
    };
  } 
} 
</script>

<style lang="stylus" scoped>
.operation-menu-wrapper.file-type-6
  margin 8px 0
  justify-content flex-end

.operation-menu-wrapper
  padding 16px 0
  display flex
  justify-content space-between
  align-items: center;

  .operate-group
    flex 1

  .change-image-model,
  .change-file-model
    margin-right 8px

  .batch-opera-btn
    margin-right 8px

  .select-file-input {
    margin-right: 8px;
    width: 200px;

    .el-icon-search {
      cursor: pointer;
      font-size: 16px;

      &:hover {
        color: Primary;
      }
    }
  }
</style>
